<template>
  <div class="upload-file">
    <a-upload
      :action="action"
      :headers="headers"
      :multiple="true"
      :file-list="fileLists"
      @preview="handlePreview"
      @change="handleChange"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :showUploadList="showUploadList"
    >
      <a-button
        type="primary"
        :disabled="disabled"
        :size="buttonSize"
        v-if="buttonIs"
      >
        <a-icon type="upload" v-if="iconIs" /> {{text}}
      </a-button>
    </a-upload>

    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancel"
    >
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage"
      />
    </a-modal>
  </div>
</template>

<script>
import storage from "store";
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  props: {
    // 显示文件列表
    fileList: { type: Array, default: () => [] },
    text: {
      type: String,
      default: "上传",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    buttonSize: {
      type: String,
      default: "default",
    },
    num: {
      type: Number,
      default: null,
    },
    //文件上传类型
    fileTypes: {
      type: Array,
      default: () => ["png", "PNG", "jpg", "JPG", "jpeg", "JPEG"],
    },
    // 限制上传大小  单位M
    size: {
      type: Number,
      default: 100,
    },
    // 是否显示按钮
    buttonIs: {
      type: Boolean,
      default: true,
    },
    //是否显示icon
    iconIs: {
      type: Boolean,
      default: true,
    },
    showUploadList:{
      type: Boolean,
      default: true,
    }
  },

  data() {
    return {
      action: `${process.env.VUE_APP_API_BASE_URL}/cms/file/uploadFile`,
      previewVisible: false,
      previewImage: "",
      fileLists: [],
      headers: {
        authorization: "authorization-text",
        source: this.$configs.source,
        tokenId: storage.get("Access-Token"),
      },
    };
  },
  watch: {
    fileList(value) {
      // console.log("watch===", value);
      this.fileLists = value;
    },
  },
  created() {
    this.fileLists = this.fileList;
  },
  methods: {
    handleCancel() {
      this.previewVisible = false;
    },

    async handlePreview(file) {
      console.log(file);
      if(file.response){
        window.open(file.response.data.accessUrl)
      }else {
        window.open(file.url)
      }

// window.open(`https://www.cnblogs.com/guorongtao/`); 
      // if (
      //   file.url.includes("PNG") ||
      //   file.url.includes("png") ||
      //   file.url.includes("JPG") ||
      //   file.url.includes("jpg") ||
      //   file.url.includes("JPEG") ||
      //   file.url.includes("jpeg") ||
      //   file.url.includes("WEBP") ||
      //   file.url.includes("webp")
      // ) {
      //   if (!file.url && !file.preview) {
      //     file.preview = await getBase64(file.originFileObj);
      //   }
      //   this.previewImage = file.url || file.preview;
      //   this.previewVisible = true;
      // }
    },
    handleChange(info) {
      let { fileList } = info;
      if (this.num == 1) {
        fileList = fileList.slice(-1);
      }
      if (info.file.status == "done") {
        if (info.file.response.code == 0) {
          this.$emit("success", info.file.response.data);
          this.$emit("input", info.file.response.data);
        }
      }
      // this.$emit("successFile", [...fileList]);
      this.fileLists = fileList;
      if (info.file.response) {
        if (info.file.response.code == 100003) {
          this.$notification.error({
            message: "登录失效",
            description: "登录失效,请重新登录",
          });
          setTimeout(() => {
            storage.remove("Access-Token");
            storage.remove("User-Info");
            window.location.href = "/user/login";
          }, 2000);
        } else if (
          info.file.response.code != 0 &&
          info.file.response.code != 100003
        ) {
          this.fileList = [];
          this.$notification.error({
            message: "失败",
            description: info.file.response.msg,
          });
        }
      }
    },
    beforeUpload(info) {
      // console.log("this.fileList.length -----", this.fileList.length);
      // if (this.fileList.length >= 1) {
      //   this.$message.info(`请先删除后，再上传`);
      //   return false;
      // }
      // console.log("beforeUpload-----", info);
      // if (!this.typeCheck(info.name)) {
      //   this.$message.info(`请上传以下格式${this.fileTypes}文件`);
      //   return false;
      // }
      // if (!this.sizeCheck(info.size)) {
      //   this.$message.info(`请上传${this.size}M以下的文件`);
      //   return false;
      // }
    },
    //, 检查文件大小
    sizeCheck(sizeFile) {
      if (this.size * 1024 * 1024 > sizeFile) {
        return true;
      } else {
        return false;
      }
    },
    // 检查文件类型
    typeCheck(name) {
      let arr = name.split(".");
      let type = arr[arr.length - 1];
      console.log(arr[arr.length - 1]);

      if (this.fileTypes.includes(type)) {
        return true;
      } else {
        return false;
      }
    },
    // 删除文件
    remove(file) {
      console.log(file);
    },
  },
};
</script>

<style lang="less" scoped>
.upload-file {
  display: inline-block;
  width: 100%;
}
</style>>
 